﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using qltscd.Models;
using qltscd.Models.ScreenClient;
using qltscd.Contansts;
using Telerik.Web.Mvc;
using qltscd.Helper;
using qltscd.Contansts;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using CrystalDecisions.Shared;
using System.Text;
using System.Web.Routing;

namespace qltscd.Controllers
{
    public class DanhMucNguoiDungController : BaseController
    {
        protected override void OnActionExecuting (ActionExecutingContext filterContext) {
            base.OnActionExecuting(filterContext);
            if (SessionHelper.QuyenNhom[qltscd.Contansts.KeyContansts.QuyenDanhMuc] == '0') {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {
                    controller = "KhongCoQuyen",
                    action = "Index"
                }));
            }
        }
        #region Properties Section
        private QLTBEntities db = new QLTBEntities();
        #endregion

        #region Views Section
        public ViewResult Index()
        {
            DMNDScreenClient screen = new DMNDScreenClient();
            if (Session[SessionScreenContansts.DanhMucNguoiDung_SCREENCLIENT] != null) {
                screen = (DMNDScreenClient)Session[SessionScreenContansts.DanhMucNguoiDung_SCREENCLIENT];
            }
            Search(screen);
            ViewBag.MaNguoiDung = new SelectList(db.DanhMucNguoiDungs, "IdentityNguoiDung", "TenNguoiDung");
            ViewBag.MaNhomNguoiDung = new SelectList(db.DanhMucNhomNguoiDungs.OrderBy(i => i.TenNhomNguoiDung), "IdentityNhomNguoiDung", "TenNhomNguoiDung");
            return View(screen);
        }
        [HttpPost]
        public ActionResult Index (DMNDScreenClient screen) {
            Search(screen);
            ViewBag.MaNguoiDung = new SelectList(db.DanhMucNguoiDungs, "IdentityNguoiDung", "TenNguoiDung");
            ViewBag.MaNhomNguoiDung = new SelectList(db.DanhMucNhomNguoiDungs.OrderBy(i => i.TenNhomNguoiDung), "IdentityNhomNguoiDung", "TenNhomNguoiDung");
            return View(screen);
        }

        [GridAction]
        public ActionResult _Index () {
            DMNDScreenClient screen = new DMNDScreenClient();
            if (Session[SessionScreenContansts.DanhMucNguoiDung_SCREENCLIENT] != null) {
                screen = (DMNDScreenClient)Session[SessionScreenContansts.DanhMucNguoiDung_SCREENCLIENT];
            }
            Search(screen);
            return View(new GridModel(screen.DSNguoiDung));
        }

        public ActionResult Create () {
            ViewBag.IdentityNguoiDung = new SelectList(db.DanhMucNguoiDungs, "IdentityNguoiDung", "TenNguoiDung");
            ViewBag.IdentityNhomNguoiDung = new SelectList(db.DanhMucNhomNguoiDungs, "IdentityNhomNguoiDung", "TenNhomNguoiDung");
            ViewBag.IdentityDonVi = new SelectList(db.DanhMucDonViQuanLies.OrderBy(i => i.MaDonVi), "IdentityDonVi", "TenDonVi");
            Models.BaseClient.DanhMucNguoiDung nd = new Models.BaseClient.DanhMucNguoiDung() { IdentityNguoiDung = -1 };
            return View(nd);
        }

        public ActionResult TaoNguoiDung()
        {
            ViewBag.IdentityNguoiDung = new SelectList(db.DanhMucNguoiDungs, "IdentityNguoiDung", "TenNguoiDung");
            ViewBag.IdentityNhomNguoiDung = new SelectList(db.DanhMucNhomNguoiDungs, "IdentityNhomNguoiDung", "TenNhomNguoiDung");
            Models.BaseClient.DanhMucNguoiDung nd = new Models.BaseClient.DanhMucNguoiDung() { IdentityNguoiDung = -1 };
            return View(nd);
        }

        public ActionResult XoaNguoiDung()
        {
            string id = Request.QueryString["id"];
            //DanhMucNguoiDung nd = db.DanhMucNguoiDungs.Single(i => i.IdentityNguoiDung == checkedRecord);
            try
            {
                if (id != null)
                {
                    int iden = Convert.ToInt32(id);
                    DanhMucNguoiDung nd = db.DanhMucNguoiDungs.Single(i => i.IdentityNguoiDung == iden);
                    db.DanhMucNguoiDungs.DeleteObject(nd);
                    db.SaveChanges();
                    return RedirectToAction("Index");

                }
                else
                {
                    return RedirectToAction("Index");
                }
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }

        public ActionResult ShowPdf()
        {
            ReportClass rpt = new ReportClass();
            rpt.FileName = Server.MapPath("~/") + "//Reports//rDanhMucNguoiDung.rpt";
            rpt.SetDatabaseLogon("sa", "sa");
            rpt.Load();
            //rpt.SetDataSource(db.DanhMucNguoiDungs);
            Stream stream = rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
            return File(stream, "application/pdf");
        }

        public FileResult ExportToExcel()
        {

            DataTable myTable = new DataTable();

            var data = from n in db.DanhMucNguoiDungs
                       select n;

            myTable.Columns.Add("Mã Người Dùng");
            myTable.Columns.Add("Họ Tên Đệm");
            myTable.Columns.Add("Tên Người Dùng");
            myTable.Columns.Add("Tên Đăng Nhập");
            myTable.Columns.Add("Mật Khẩu");
            myTable.Columns.Add("Hộp Thư");

            foreach (var n in data)
            {
                myTable.Rows.Add(n.MaNguoiDung.ToString(), n.HoTenDem, n.TenNguoiDung.ToString(), n.TenDangNhap, n.MatKhau, n.HopThu);
            }

            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + "BaoCaoDanhMucNguoiDung.xls");
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());

            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("DANH MỤC NGƯỜI DÙNG\t\t\t\n\n");
                for (int count = 0; count < myTable.Columns.Count; count++)
                {
                    if (myTable.Columns[count].ColumnName != null)
                        sb.Append(myTable.Columns[count].ColumnName);
                    if (count < myTable.Columns.Count - 1)
                        sb.Append("\t");
                }

                Response.Write(sb.ToString() + "\n");
                Response.Flush();
                int soDem = 0;
                while (myTable.Rows.Count >= soDem + 1)
                {
                    sb = new StringBuilder();
                    for (int col = 0; col < myTable.Columns.Count - 1; col++)
                    {
                        if (myTable.Rows[soDem][col] != null)
                            sb.Append(myTable.Rows[soDem][col].ToString().Replace(",", " "));
                        sb.Append("\t");
                    }
                    if (myTable.Rows[soDem][myTable.Columns.Count - 1] != null)
                        sb.Append(myTable.Rows[soDem][myTable.Columns.Count - 1].ToString().Replace(",", " "));
                    Response.Write(sb.ToString() + "\n");
                    Response.Flush();
                    soDem = soDem + 1;
                }
            }
            catch
            {

            }

            myTable.Dispose();
            Response.End();
            return File("BaoCaoDanhMucNguoiDung", "application/ms-excel", "BaoCaoDanhMucNguoiDung.xls");
        }

        public ActionResult ExportExcel () {
            ReportClass cryRpt = new ReportClass();
            cryRpt.FileName = Server.MapPath("~/") + "//Reports//rDanhMucNguoiDung.rpt";
            cryRpt.Load();
            ExportOptions CrExportOptions;
            DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
            ExcelFormatOptions CrFormatTypeOptions = new ExcelFormatOptions();
            CrDiskFileDestinationOptions.DiskFileName = "csharp.net-informations.xls";
            CrExportOptions = cryRpt.ExportOptions;
            CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
            CrExportOptions.ExportFormatType = ExportFormatType.Excel;
            CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
            CrExportOptions.FormatOptions = CrFormatTypeOptions;
            cryRpt.Export();
            return RedirectToAction("Index");
        }

        public ActionResult Print () {
            ReportClass rpt = new ReportClass();
            rpt.FileName = Server.MapPath("~/") + "//Reports//rDanhMucNguoiDung.rpt";
            rpt.Load();
            rpt.PrintToPrinter(1, false, 0 ,0);
            return RedirectToAction("Index");
        }

        public ActionResult SuaNguoiDung()
        {
            ViewBag.IdentityNhomNguoiDung = new SelectList(db.DanhMucNhomNguoiDungs, "IdentityNhomNguoiDung", "TenNhomNguoiDung");
            ViewBag.IdentityDonVi = new SelectList(db.DanhMucNguoiDungs, "IdentityDonVi");
            string id = Request.QueryString["id"];
            if (id != null)
            {
                int iden = Convert.ToInt32(id);
                DanhMucNguoiDung nd = db.DanhMucNguoiDungs.Single(i => i.IdentityNguoiDung == iden);
                Models.BaseClient.DanhMucNguoiDung ndC = new Models.BaseClient.DanhMucNguoiDung();
                ObjectHelper.Copy(nd, ndC);
                return View(ndC);

            }
            else
            {
                return RedirectToAction("Index");
            }
        }
        #endregion

        #region CRUD Section
        [HttpPost]
        public ActionResult SuaNguoiDung(Models.BaseClient.DanhMucNguoiDung ndC)
        {
            ViewBag.IdentityNhomNguoiDung = new SelectList(db.DanhMucNhomNguoiDungs, "IdentityNhomNguoiDung", "TenNhomNguoiDung", ndC.IdentityNhomNguoiDung);
            ViewBag.IdentityDonVi = new SelectList(db.DanhMucDonViQuanLies.OrderBy(o => o.MaDonVi), "IdentityDonVi", "TenDonVi", ndC.IdentityNhomNguoiDung);
            if (ModelState.IsValid)
            {
                //code de luu lai
                DanhMucNguoiDung h = db.DanhMucNguoiDungs.Single(i => i.IdentityNguoiDung == ndC.IdentityNguoiDung);
                if (ndC.MaNguoiDung != h.MaNguoiDung) {
                    if (db.DanhMucNguoiDungs.Count(i => i.MaNguoiDung == ndC.MaNguoiDung) > 0) {
                        ViewData[qltscd.Contansts.SessionConstants.ERROR_MESSAGE] = "Mã " + ndC.MaNguoiDung + " đã tồn tại";
                        return View(ndC);
                    }
                }
                ObjectHelper.Copy(ndC, h);
                db.ObjectStateManager.ChangeObjectState(h, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(ndC);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _SaveBatchEditing ([Bind(Prefix = "inserted")]IEnumerable<qltscd.Models.BaseClient.DanhMucNguoiDung> inserted,
             [Bind(Prefix = "updated")]IEnumerable<qltscd.Models.BaseClient.DanhMucNguoiDung> updated,
             [Bind(Prefix = "deleted")]IEnumerable<qltscd.Models.BaseClient.DanhMucNguoiDung> deleted) {
            if (inserted != null) {
                foreach (var userClient in inserted) {
                    DanhMucNguoiDung user = new DanhMucNguoiDung();
                    db.DanhMucNguoiDungs.AddObject(user);
                }
            }
            if (updated != null) {
                foreach (var userClient in updated) {
                    DanhMucNguoiDung user = db.DanhMucNguoiDungs.Single(i => i.MaNguoiDung == userClient.MaNguoiDung);
                    ObjectHelper.Copy(user, userClient);
                    db.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
                }
            }
            if (deleted != null) {
                foreach (var userClient in deleted) {
                    DanhMucNguoiDung user = db.DanhMucNguoiDungs.Single(i => i.MaNguoiDung == userClient.MaNguoiDung);
                    db.DanhMucNguoiDungs.DeleteObject(user);
                }
            }
            db.SaveChanges();
            DMNDScreenClient screen = (DMNDScreenClient)Session[SessionScreenContansts.DanhMucNguoiDung_SCREENCLIENT];
            Search(screen);
            return View(new GridModel(screen.DSNguoiDung));
        }

        [HttpPost]
        public ActionResult Create (qltscd.Models.BaseClient.DanhMucNguoiDung uClient) {
            if (ModelState.IsValid) {
                DanhMucNguoiDung u = new DanhMucNguoiDung();
                if (uClient.IdentityNguoiDung == -1)
                {
                    //uClient.MaNguoiDung = DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
                    if (uClient.MaNguoiDung != u.MaNguoiDung)
                    {
                        if (db.DanhMucNguoiDungs.Count(o => o.MaNguoiDung == uClient.MaNguoiDung) > 0)
                        {
                            ViewData[SessionConstants.ERROR_MESSAGE] = "Mã người dùng " + uClient.MaNguoiDung + " đã tồn tại";
                            ViewBag.IdentityNhomNguoiDung = new SelectList(db.DanhMucNhomNguoiDungs, "IdentityNhomNguoiDung", "TenNhomNguoiDung", uClient.IdentityNhomNguoiDung);
                            ViewBag.IdentityDonVi = new SelectList(db.DanhMucDonViQuanLies.OrderBy(o => o.MaDonVi), "IdentityDonVi", "TenDonVi", uClient.IdentityNhomNguoiDung);
                            return View(uClient);
                        }
                    }
                    if (uClient.TenDangNhap != u.TenDangNhap)
                    {
                        if (db.DanhMucNguoiDungs.Count(o => o.TenDangNhap == uClient.TenDangNhap) > 0)
                        {
                            ViewData[SessionConstants.ERROR_MESSAGE] = "Tên đăng nhập " + uClient.TenDangNhap + " đã tồn tại";
                            ViewBag.IdentityNhomNguoiDung = new SelectList(db.DanhMucNhomNguoiDungs, "IdentityNhomNguoiDung", "TenNhomNguoiDung", uClient.IdentityNhomNguoiDung);
                            ViewBag.IdentityDonVi = new SelectList(db.DanhMucDonViQuanLies.OrderBy(o => o.MaDonVi), "IdentityDonVi", "TenDonVi", uClient.IdentityNhomNguoiDung);
                            return View(uClient);
                        }
                    }
                    ObjectHelper.Copy(uClient, u);
                    db.DanhMucNguoiDungs.AddObject(u);
                }
                else
                {
                    u = db.DanhMucNguoiDungs.Single(i => i.IdentityNguoiDung == uClient.IdentityNguoiDung);
                    if (uClient.MaNguoiDung != u.MaNguoiDung)
                    {
                        if (db.DanhMucNguoiDungs.Count(o => o.MaNguoiDung == uClient.MaNguoiDung) > 0)
                        {
                            ViewData[SessionConstants.ERROR_MESSAGE] = "Mã người dùng " + uClient.MaNguoiDung + " đã tồn tại";
                            ViewBag.IdentityNhomNguoiDung = new SelectList(db.DanhMucNhomNguoiDungs, "IdentityNhomNguoiDung", "TenNhomNguoiDung", uClient.IdentityNhomNguoiDung);
                            ViewBag.IdentityDonVi = new SelectList(db.DanhMucDonViQuanLies.OrderBy(o => o.MaDonVi), "IdentityDonVi", "TenDonVi", uClient.IdentityNhomNguoiDung);
                            return View(uClient);
                        }
                    }
                    if (uClient.TenDangNhap != u.TenDangNhap)
                    {
                        if (db.DanhMucNguoiDungs.Count(o => o.TenDangNhap == uClient.TenDangNhap) > 0)
                        {
                            ViewData[SessionConstants.ERROR_MESSAGE] = "Tên đăng nhập " + uClient.TenDangNhap + " đã tồn tại";
                            ViewBag.IdentityNhomNguoiDung = new SelectList(db.DanhMucNhomNguoiDungs, "IdentityNhomNguoiDung", "TenNhomNguoiDung", uClient.IdentityNhomNguoiDung);
                            ViewBag.IdentityDonVi = new SelectList(db.DanhMucDonViQuanLies.OrderBy(o => o.MaDonVi), "IdentityDonVi", "TenDonVi", uClient.IdentityNhomNguoiDung);
                            return View(uClient);
                        }
                    }
                    ObjectHelper.Copy(uClient, u);
                    db.ObjectStateManager.ChangeObjectState(u, EntityState.Modified);
                }
                db.SaveChanges();
                return RedirectToAction("Create"); 
            }
            ViewBag.IdentityNhomNguoiDung = new SelectList(db.DanhMucNhomNguoiDungs, "IdentityNhomNguoiDung", "TenNhomNguoiDung", uClient.IdentityNhomNguoiDung);
            ViewBag.IdentityDonVi = new SelectList(db.DanhMucDonViQuanLies.OrderBy(o => o.MaDonVi), "IdentityDonVi", "TenDonVi", uClient.IdentityNhomNguoiDung);
            return View(uClient);
        }

        [HttpPost]
        public ActionResult TaoNguoiDung (qltscd.Models.BaseClient.DanhMucNguoiDung uClient) {
            if (ModelState.IsValid) {
                DanhMucNguoiDung u = new DanhMucNguoiDung();
                if (uClient.IdentityNguoiDung == -1) {
                    uClient.MaNguoiDung = DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
                    ObjectHelper.Copy(uClient, u);
                    db.DanhMucNguoiDungs.AddObject(u);
                } else {
                    u = db.DanhMucNguoiDungs.Single(i => i.IdentityNguoiDung == uClient.IdentityNguoiDung);
                    ObjectHelper.Copy(uClient, u);
                    db.ObjectStateManager.ChangeObjectState(u, EntityState.Modified);
                }
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.MaNguoiDung = new SelectList(db.DanhMucNguoiDungs, "IdentityNguoiDung", "TenNguoiDung");
            ViewBag.MaNhomNguoiDung = new SelectList(db.DanhMucNhomNguoiDungs, "IdentityNhomNguoiDung", "TenNhomNguoiDung");
            return View(uClient);
        }
        #endregion

        #region Helper Section
        private void Search (DMNDScreenClient screen) {
            if (Session[SessionScreenContansts.DanhMucNguoiDung_SCREENCLIENT] != null) {
                screen = (DMNDScreenClient)Session[SessionScreenContansts.DanhMucNguoiDung_SCREENCLIENT];
            } else {
                screen = new DMNDScreenClient();
            }
            screen.DSNguoiDung.Clear();
            var list = db.DanhMucNguoiDungs.OrderBy(i => i.TenNguoiDung).ToList();
            foreach (DanhMucNguoiDung DMND in list) {
                qltscd.Models.BaseClient.DanhMucNguoiDung DMNDClient = new Models.BaseClient.DanhMucNguoiDung();
                ObjectHelper.Copy(DMND, DMNDClient);
                DMNDClient.TenNguoiDung = DMND.TenNguoiDung;
                DMNDClient.TenNhomNguoiDung = DMND.DanhMucNhomNguoiDung.TenNhomNguoiDung;
                screen.DSNguoiDung.Add(DMNDClient);
            }
            Session[SessionScreenContansts.DanhMucNguoiDung_SCREENCLIENT] = screen;
        }
        #endregion

        #region Additional Section
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        #endregion
    }
}
